package com.chamber.business.service.impl;

import com.chamber.business.domain.User;
import com.chamber.business.domain.dto.UserLoginDTO;
import com.chamber.business.domain.properties.JwtProperties;
import com.chamber.business.domain.vo.UserLoginVO;
import com.chamber.business.mapper.UserMapper;
import com.chamber.business.service.UserService;
import com.chamber.common.utils.JwtUtil;
import com.chamber.common.constant.JwtClaimsConstant;
import com.chamber.common.constant.MessageConstant;
import com.chamber.common.exception.business.PasswordOrAccountException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private UserMapper userMapper;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        User user=userMapper.getUserByUsername(username);
        if (user == null)
            throw new PasswordOrAccountException(MessageConstant.ACCOUNT_NOT_FOUND);
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(userLoginDTO.getPassword())) {
            throw new PasswordOrAccountException(MessageConstant.PASSWORD_ERROR);
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        // 登录成功，返回token令牌
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(username)
                .token(token).build();
        return userLoginVO;
    }
}
